<!--  -->
<template>
  <div class="">
    <a-card class="search-wrapper">
      <div class="search-form-wrapper" ref="search">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-input v-model="queryParam.name" allow-clear placeholder="登录账号"> </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-input
                  v-model="queryParam.id"
                  allow-clear
                  placeholder="用户编号"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-input
                  v-model="queryParam.belongAgentId"
                  allow-clear
                  placeholder="上级代理商编号"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-input
                  v-model="queryParam.belongCommissionerId"
                  allow-clear
                  placeholder="上级总监编号"
                >
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-select v-model="queryParam.userType" allow-clear placeholder="所属角色">
                  <a-select-option v-for="item in ROLE_LIST" :key="item.value" :value="item.value">{{item.label}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="handle">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">
                  重置
                </a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card class="table-wrapper">
      <div style="margin-bottom: 20px">
        <a-button
          size="small"
          type="primary"
          @click="addMenu"
          v-if="userInfo.userType !== 'salesman'"
        >
          新增
        </a-button>
        <a-button size="small" type="primary" v-else @click="qrHandler">分销二维码</a-button>
        <!-- <a-button size="small" style="margin-right: 20px" @click="onMultiple({status: '0'},'批量启用')"> 批量启用 </a-button>
        <a-button size="small" @click="onMultiple({status: '1'},'批量禁用')">批量禁用</a-button> -->
      </div>
      <a-table
        :loading="tableLoading"
        :columns="
          userInfo.userType !== 'salesman'
            ? [
                ...columns,
                {
                  title: '操作',
                  // fixed: 'right',
                  scopedSlots: { customRender: 'action' },
                  dataIndex: 'action'
                  // width: 120
                }
              ]
            : columns
        "
        :pagination="pagination"
        @change="(e) => handle(e)"
        :data-source="tableData"
        :scroll="{ y: tableHeight }"
      >
        <!-- :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange
        }" -->
        <span slot="loginName" slot-scope="text, record" class="pointer" @click="editMenu(record)">
          <a-icon type="edit" theme="twoTone" class="mr-10" /> {{ text }}
        </span>
        <span slot="roles" slot-scope="text">
          {{ text | splitRoles }}
        </span>
        <span slot="statusDesc" slot-scope="text, record">
          <a-switch
            :checked="record.status == 1"
            checked-children="启用"
            un-checked-children="禁用"
            @change="(val) => onChangeStatus(record, val)"
          />
        </span>
        <span slot="action" slot-scope="text, record" v-if="userInfo.userType !== 'salesman'">
          <!-- <a type="default" @click="del(record)" v-if="record.status != 1">删除</a>
          <a-divider type="vertical" v-if="record.status != 1" /> -->
          <a-button type="link" @click="$refs.accountsForm.open(record)">编辑</a-button>
           <a-button v-if="userInfo.userType === 'commissioner' && record.userType === 'salesman'" type="link" @click="setHbMax(record)">红包额度</a-button>
        </span>
      </a-table>
    </a-card>
    <AccountsForm ref="accountsForm" @on-submit="handle" />
    <a-modal v-model="visible" title="分销二维码" :footer="null">
      <img :src="qrUrl" class="qrUrl" />
    </a-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getUserList, delUser, fetchUserAction, resetPwd } from '@/api/system'
import { shortUserList, shortUserQr, rewardHbSet } from '@/api/short'
import { ROLE_LIST } from "../../const/const"
import AccountsForm from './modal/accountForm.vue'
const columns = [
  {
    title: '用户编号',
    dataIndex: 'id'
    // scopedSlots: { customRender: 'loginName' },
  },
  {
    title: '登录账号',
    dataIndex: 'name'
    // scopedSlots: { customRender: 'loginName' },
  },
  {
    title: '上级代理商编号',
    dataIndex: 'belongAgentId'
  },
  {
    title: '上级总监编号',
    dataIndex: 'belongCommissionerId'
  },
  {
    title: '红包总额度',
    dataIndex: 'hbMax'
  },
  {
    title: '红包余额',
    dataIndex: 'hbBalance'
  },
  {
    title: '状态',
    dataIndex: 'statusDesc',
    scopedSlots: { customRender: 'statusDesc' },
  },
  {
    title: '角色',
    dataIndex: 'userTypeDesc'
  },
  {
    title: '角色说明',
    dataIndex: 'userInfo'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  // {
  //   title: '操作',
  //   // fixed: 'right',
  //   scopedSlots: { customRender: 'action' },
  //   dataIndex: 'action',
  //   // width: 120
  // }
]
export default {
  components: {
    AccountsForm
  },
  data() {
    return {
      visible: false,
      ROLE_LIST,
      pagination: {
        current: 1,
        'show-size-changer': true,
        total: 0
      },
      tableData: [],
      tableLoading: false,
      advanced: false,
      queryParam: {
        pageSize: 10,
        pageNum: 1
      },
      tabbarHeight: 420,
      columns,
      menuForm: {
        orgId: '',
        jobNumber: '',
        name: '',
        loginPhone: '',
        position: '',
        email: ''
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      rules: {
        parentId: [{ required: true, message: '请选择归属机构' }],
        jobNumber: [{ required: true, message: '请输入统一认证号' }],
        name: [{ required: true, message: '请选择员工姓名' }]
      },
      act: 'add',
      parentList: [],
      identifiesTypeList: [],
      typeIndex: 0,
      roleVisible: false,
      targetKeys: [],
      selectedKeys: [],
      allRoleList: [],
      confirmLoading: false,
      userIds: [],
      selectedRowKeys: [],
      selectedRows: [],
      qrUrl: ''
    }
  },
  filters: {
    splitRoles: function (value) {
      return value && value.join('，')
    }
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    tableHeight() {
      return document.body.clientHeight - 220
    },
    ...mapState({
      userInfo: (state) => state.user.info
    })
  },
  activated() {
    this.loadData()
  },
  mounted() {
    this.loadData()
  },
  methods: {
    setHbMax(r) {
      let hbMax = r.hbMax || ''
      const vm = this
      console.log(r,hbMax, 'r.hbMax');
      this.$confirm({
        title: '设置红包发放额度',
        width: 540,
        content: (
          <div>
            <a-input
              placeholder="请输入设置红包发放额度"
              allow-clear
              value={hbMax}
              onChange={(e) => (hbMax = e.target.value)}
            ></a-input>
          </div>
        ),
        class: 'confirm-box',
        onOk() {
          return new Promise((resolve, reject) => {
            if (!hbMax) {
              vm.$message['error']('请输入设置红包发放额度')
              return reject(new Error('请输入设置红包发放额度'))
            } else if(!/(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0){1}$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/.test(hbMax)){
              vm.$message['error']('请输入正确的金额')
              hbMax = ''
              return reject(new Error('请输入正确的金额'))
            } else {
              rewardHbSet({userId: r.id, hbMax})
                .then((resp) => {
                  vm.$notification['success']({
                    message: '成功提示',
                    description: `设置成功`
                  })
                  // vm.selectedRowKeys = []
                  // vm.selectedRows = []
                  vm.handle()
                  resolve()
                })
                .catch((error) => {
                  return reject(new Error(error))
                })
            }
          })
        }
      })
    },
    qrHandler() {
      shortUserQr().then((resp) => {
        this.qrUrl = resp.data
        this.visible = true
      })
    },
    onMultiple(record, msg) {
      if (!this.selectedRows.length) {
        this.$notification['error']({
          message: '错误提示',
          description: `请选择${msg}数据`
        })
      } else {
        this.onChangeStatus(record)
      }
    },
    onChangeStatus(record, value) {
      const vm = this
      let idList = []
      if (record.id) {
        idList = [record.id]
      } else {
        idList = this.selectedRows.map((v) => v.id)
      }
      const type = record.status == 1 ? 'disable' : 'able'
      console.log(record, value, 'record, value')
      this.$confirm({
        title: record.status == 1 ? '禁用' : '启用',
        content: (
          <div>
            {record.status == '1' ? (
              <p>
                <span style="color:#FF4E4E">账号禁用后，将无法登录任何系统</span>，你还要继续吗？
              </p>
            ) : (
              <p>确认启用该登录账号？</p>
            )}
          </div>
        ),
        class: 'confirm-box',
        onOk() {
          return new Promise((resolve, reject) => {
            fetchUserAction({ idList }, type)
              .then(() => {
                vm.$notification['success']({
                  message: '成功提示',
                  description: record.status == 1 ? '账号禁用成功' : '账号启用成功'
                })
                vm.selectedRowKeys = []
                vm.selectedRows = []
                vm.loadData()
                resolve()
              })
              .catch(() => {
                return reject(new Error(''))
              })
          })
        }
      })
    },
    loadData() {
      this.tableLoading = true
      this.queryParam.layerType = String(this.typeIndex - 0 + 1)
      shortUserList({ ...this.queryParam })
        .then((res) => {
          this.tableLoading = false
          console.log(res)
          this.tableData = res.data.records
          this.pagination.total = res.data.total
          this.tableData.forEach((item) => {
            const roleName = item.roles.map((temp) => {
              return temp.name
            })
            const roleIds = item.roles.map((temp) => {
              return String(temp.id)
            })
            item.roleName = roleName.join(',')
            item.roleIds = roleIds
          })
        })
        .catch(() => {})
    },
    handle(v) {
      if (v && v.current) {
        if (this.queryParam.pageSize == v.pageSize) {
          this.pagination.current = v.current
          this.queryParam.pageNum = v.current
        } else {
          this.queryParam.pageSize = v.pageSize
          this.queryParam.pageNum = 1
          this.pagination.current = 1
        }
      } else {
        this.queryParam.pageNum = 1
        this.pagination.current = 1
      }
      this.loadData()
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    addMenu() {
      this.$refs.accountsForm.open()
    },
    editMenu(info) {
      this.$refs.accountsForm.open(info)
    },
    del(info) {
      const vm = this
      this.$confirm({
        title: '删除账号',
        content: (
          <div>
            {
              <p>
                <span style="color:#FF4E4E">账号删除后，将无法登录任何系统</span>，你还要继续吗？
              </p>
            }
          </div>
        ),
        onOk() {
          return new Promise((resolve, reject) => {
            delUser(info.id)
              .then(() => {
                vm.$notification['success']({
                  message: '提示',
                  description: '删除成功'
                })
                vm.loadData()
                vm.selectedRowKeys = []
                vm.selectedRows = []
                resolve()
              })
              .catch(() => {
                return reject(new Error(''))
              })
          })
        }
      })
    },
    resetPassword(info) {
      const vm = this
      this.$confirm({
        title: '重置密码',
        content: '请确认是否重置密码？',
        onOk() {
          return new Promise((resolve, reject) => {
            resetPwd({ userId: info.id })
              .then(() => {
                vm.$notification['success']({
                  message: '提示',
                  description: '操作成功'
                })
                vm.loadData()
                resolve()
              })
              .catch(() => {
                return reject(new Error(''))
              })
          })
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>

<style lang="less" scoped>
.qrUrl {
  width: 100%;
  height: 100%;
}
</style>
